﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SGRapidForm.Common;
using System.IO;
using DevExpress.Web.ASPxUploadControl;
using SGRapidForm.Permission.Service.Interface;
using System.Xml;
using SGRapidForm.Permission.Entity;

namespace SGDemo.Permission
{
    public partial class ImportButtonData : System.Web.UI.Page
    {
        private IPermissionService _permissionService = ServiceProxyFactory.Create<IPermissionService>("permissionservice");

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        const string UploadDirectory = "~/UploadFile/Permission/";

        /// <summary>
        /// 上传文件完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void uplImage_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile);
        }

        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="uploadedFile"></param>
        public string SavePostedFile(UploadedFile uploadedFile)
        {
            if (!uploadedFile.IsValid)
            {
                return "{isSucess:false,msg:'上传文件无效'}";
            }

            string fileName = Path.Combine(MapPath(UploadDirectory), uploadedFile.FileName);
            uploadedFile.SaveAs(fileName, true);
            return ImportData(fileName);
        }

        /// <summary>
        /// 导入一个页面的按钮数据
        /// </summary>
        /// <remarks>
        /// 1，检测页面是否存在，存在则删除此页面下的所有按钮信息
        /// 2，获取此页面的Keyid和所属ModuleKeyid
        /// 3，遍历XML按钮节点，添加到按钮表中
        /// 4，删除上传的XML文档
        /// </remarks>
        protected string ImportData(string absolutePath)
        {
            string pageCode = Path.GetFileNameWithoutExtension(absolutePath);
            if (!_permissionService.Button_DetectBeforeImporting(pageCode))
            {
                return "{isSucess:false,msg:'找不到导入按钮所属页面'}";

            }
            try
            {
                PageEntity page = _permissionService.Page_GetKeyidBypagename(pageCode);
                XmlDocument doc = new XmlDocument();
                doc.Load(absolutePath);
                XmlElement rootElem = doc.DocumentElement;
                XmlNodeList personNodes = rootElem.GetElementsByTagName("item");

                ButtonEntity btn = new ButtonEntity();
                foreach (XmlNode node in personNodes)
                {
                    btn.Keyid = Guid.NewGuid().ToString();
                    btn.ButtonCode = ((XmlElement)node).GetAttribute("Name");
                    btn.ButtonName = ((XmlElement)node).GetAttribute("Text");
                    btn.ButtonNameEn = ((XmlElement)node).GetAttribute("EnglishText");
                    btn.ButtonType = ((XmlElement)node).GetAttribute("ButtonType");
                    btn.ImageUrl = ((XmlElement)node).GetAttribute("ImageUrl");
                    btn.OnClick = ((XmlElement)node).GetAttribute("NavigateUrl");
                    btn.Order = int.Parse(((XmlElement)node).GetAttribute("Order"));
                    btn.Remark = ((XmlElement)node).GetAttribute("Remark");
                    btn.ServerSideMethod = ((XmlElement)node).GetAttribute("ServerSideMethod");
                    btn.ModuleKeyid = page.ModuleKeyid;
                    btn.PageKeyid = page.Keyid;
                    btn.CreateDate = System.DateTime.Now;
                    btn.CreateName = ApplicationContext.Current.UserName;

                    _permissionService.Button_Add(btn);
                }

                File.Delete(absolutePath);
            }
            catch(Exception e)
            {
                return "{isSucess:false,msg:'"+e.Message+"'}";
            }

            return "{isSucess:true,msg:'导入成功！'}";
        }
    }
}